//################################
// 版权所有：鸽子游戏俱乐部
// 系统名称：鸽子游戏俱乐部-移动版
// 文件名称：my.js
// 创建时间：2017年04月20日
// 创建人员：Lemo
// 功能说明：my page
//################################

'use strict';

import React, {Component} from 'react';
import {
    View,
    StyleSheet,
    ScrollView,
    Text,
    ListView,
    Dimensions,
    TouchableOpacity,
    TouchableHighlight,
    InteractionManager,
    Image,
    Linking,
    Alert,
} from 'react-native';

import {
    UIConstants,
    Colors,
    FontSizes,
    PubSubTopics,
    CommonData,
    CommonFunc,
    Routes,
} from '../../common';

import Images from '../../images';
import MyItem from './myItem';
import MyProfileItem from './myProfileItem';
import PubSub from 'pubsub-js';
import LocalStorage from '../../utils/storageUtil';
import UUID from 'react-native-uuid';
import * as ActionTypes from '../../actions/types';
import GiftedListView from '../../components/pandaListView';
import {toastTip} from '../../utils/toastTipUtil';
import MyFundHistoryContainer from '../containers/myFundHistoryContainer';

import {getRentGamesList, getReturnGamesList} from '../../actions';

const WINDOW_WIDTH = Dimensions.get('window').width;
const WINDOW_HEIGHT = Dimensions.get('window').height;

class My extends Component {
    constructor(props) {
        super(props);

        //租借列表
        this.renderRow = this.renderRowFunc.bind(this);
        this.onFetch = this.onFetchFunc.bind(this);
        this.renderEmptyView = this.renderEmptyViewFunc.bind(this);

        this.onFetch2 = this.onFetch2Func.bind(this);

        this.onPressCharge = this.onPressChargeFunc.bind(this);
        this.onPressHistory = this.onPressHistoryFunc.bind(this);
        this.hasGesturePassword = false;

    }

    componentDidMount() {
        LocalStorage.getUserList((userList) => {this.gotUserList(userList)});
    }

    componentWillReceiveProps(nextProps) {
        switch (nextProps.actionType) {
            case ActionTypes.MY_RENTLIST_SUCCESS:
                this._getRentSuccess(nextProps.rentgamelist);
                break;
            case ActionTypes.MY_RENTLIST_FAILED:
                this.errorHandler(nextProps.rentgamelisterrormsg);
                break;
            case ActionTypes.MY_RETURNLIST_SUCCESS:
                this._getReturnSuccess(nextProps.returngamelist);
                break;
            case ActionTypes.MY_RETURNLIST_FAILED:
                this.errorHandler(nextProps.returngamelisterrormsg);
                break;
            default:
                break;
        }
    }

    _onSysClicked(data) {
        alert(data.name);
    }

    renderRowFunc(rowData) {
        return (
            <View style={{width:90,margin:2,alignItems:'center',borderRightColor:'#EAEAEA',borderRightWidth:1}}>
                <View>
                    <Image source={Images.cover001} style={styles.renderrowimage} resizeMode={Image.resizeMode.contain} />
                </View>
                <View style={{alignItems:'center'}}>
                    <View>
                        <Text style = {[styles.renderrowtext,{color:'#333333'}]} numberOfLines={1}>{rowData.GameName}</Text>
                    </View>
                    <View>
                        <Text style = {styles.renderrowtext} numberOfLines={1}>{rowData.ExpressCom}</Text>
                    </View>
                </View>
            </View>
        );
    }

    onFetchFunc(page = 1, callback, options) {
        this.callback = callback;
        const {dispatch} = this.props;
        dispatch(getRentGamesList(CommonData.userId));
    }

    renderEmptyViewFunc(refreshCallback) {
        return (
            <View style={styles.defaultView}>
                <Text style={styles.defaultViewTitle}>
                    {'暂无游戏'}
                </Text>
            </View>
        );
    }

    _getRentSuccess(listdata) {
        // let newList = JSON.parse(listdata);
        let newList = listdata;
        if (CommonFunc.isEmpty(newList)) {
            this.callback && this.callback([], {allLoaded: true});
        } else {
            this.listView._updateRows(newList, {allLoaded: true});
        }
    }

    onFetch2Func(page = 1, callback, options) {
        this.callback2 = callback;
        const {dispatch} = this.props;
        dispatch(getReturnGamesList(CommonData.userId));
    }
    
    _getReturnSuccess(listdata) {
        let newList = listdata;
        if (CommonFunc.isEmpty(newList)) {
            this.callback2 && this.callback2([], {allLoaded: true});
        } else {
            this.listView2._updateRows(newList, {allLoaded: true});
        }
    }

    onPressChargeFunc(){
        alert('充值啦~');
    }

    onPressHistoryFunc(){
        // alert('充值、消费历史~');
        const {navigatorRoot} = this.props;
        InteractionManager.runAfterInteractions(()=>{
            navigatorRoot.push({
                name: Routes.MY_FUNDHISTORY,
                component: MyFundHistoryContainer,
                friend: true,
            });
        });
    }

    errorHandler(msg) {
        toastTip(msg, 'long');
    }

    gotUserList(userList) {
        if (userList === null) {
            userList = [];
        }

        // 找到最近一次登录的用户信息
        for (let i = 0;i < userList.length;i++) {
            let user = userList[i];

            if (user.lastLogined) {
                if (userList[i].gesturePwd !== '') {
                    this.hasGesturePassword = true;
                }
                break;
            }
        }
    }

    render() {
        return (
			<View style={styles.container}>
                
                <View style={styles.splitter} />
                <MyProfileItem 
                    itemName={'会员号：'+CommonData.vipId} 
                    itemLocation={'欢迎回到鸽子游戏俱乐部'} 
                    imageSource={Images.Logo}
                />
                <View style={styles.splitter} />
                
                <View style={styles.emptyview} />

                <View style={styles.splitter} />
                <View style={[styles.itemview,{flexDirection:'row'}]}>
                    <Text style={styles.itemtext}>{'旺旺号：'+CommonData.wangwang}</Text>
                    <Text style={styles.viplevel}>{CommonData.levelName}</Text>
                </View>
                <View style={styles.middlersplitter} />
                <View style={styles.itemview}>
                    <Text style={styles.itemtext}>{'会　龄：233天'}</Text>
                </View>
                <View style={styles.middlersplitter} />
                <View style={styles.itemview}>
                    <Text style={styles.itemtext}>{'微信号：123456789'}</Text>
                </View>
                <View style={styles.middlersplitter} />
                <View style={styles.itemview}>
                    <Text style={styles.itemtext}>{'鸽子币：'+CommonData.balance}</Text>
                    <TouchableHighlight onPress={this.onPressCharge} underlayColor="rgba(34,26,38,0.1)" style={styles.button}>
                        <Text style={{color:'#FFFFFF'}} >{'充值'}</Text>
                    </TouchableHighlight>
                    <TouchableHighlight onPress={this.onPressHistory} underlayColor="rgba(34,26,38,0.1)" style={styles.button}>
                        <Text style={{color:'#FFFFFF'}} >{'资金历史'}</Text>
                    </TouchableHighlight>
                </View>
                <View style={styles.middlersplitter} />
                <View style={styles.itemview}>
                    <Text style={styles.itemtext}>{'押　金：100RMB'}</Text>
                </View>
                <View style={styles.splitter} />

                <View style={styles.emptyview} />

                <View style={styles.splitter} />
                <View style={styles.lists}>
                    <View style={styles.listview}>
                        <View style={styles.listTitle}><Text>{'借'}</Text></View>
                        <GiftedListView
                            ref={(ref) => {this.listView = ref}}
                            horizontal={true}
                            rowView={this.renderRow}
                            onFetch={this.onFetch}
                            initialListSize={3} // the maximum number of rows displayable without scrolling (height of the listview / height of row)
                            firstLoader={true} // display a loader for the first fetching
                            pagination={false} // enable infinite scrolling using touch to load more
                            refreshable={false} // enable pull-to-refresh for iOS and touch-to-refresh for Android
                            emptyView={this.renderEmptyView}
                        />
                    </View>
                    <View style={[styles.middlersplitter,{marginLeft:0}]} />
                    <View style={styles.listview}>
                        <View style={styles.listTitle}><Text>{'还'}</Text></View>
                        <GiftedListView
                            ref={(ref) => {this.listView2 = ref}}
                            horizontal={true}
                            rowView={this.renderRow}
                            onFetch={this.onFetch2}
                            initialListSize={3} // the maximum number of rows displayable without scrolling (height of the listview / height of row)
                            firstLoader={true} // display a loader for the first fetching
                            pagination={false} // enable infinite scrolling using touch to load more
                            refreshable={false} // enable pull-to-refresh for iOS and touch-to-refresh for Android
                            emptyView={this.renderEmptyView}
                        />
                    </View>
                </View>
                <View style={styles.splitter} />
                
                
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'transparent',
    },
    splitter: {
        borderColor: Colors.mySplitter,
        borderWidth: 0.4,
    },
    itemview: {
        backgroundColor: Colors.appBackground,
        height:38,
        flexDirection: 'row',
        alignItems:'center',
        justifyContent:'flex-start',
        paddingLeft:20,
        paddingRight:20
    },
    itemtext: {
        color: '#000000',
    },
    viplevel: {
        marginLeft: 10,
        borderWidth:0.4,
        borderRadius: 3,
        padding: 3,
        fontSize: 9,
        borderColor:'#CDCD00',
        color:'#CDCD00'
    },
    button: {
        marginLeft: 20,
        padding: 3,
        paddingLeft: 10,
        paddingRight: 10,
        alignItems: 'center',
        borderRadius: 5,
        backgroundColor: '#CDCD00'
    },
    middlersplitter: {
        marginLeft: 16,
        borderColor: Colors.mySplitter,
        borderWidth: 0.3,
    },
    emptyview: {
        flex: 1,
        height: 10,
        backgroundColor: 'transparent',
    },
    lists: {
        flex: 1,
        height: WINDOW_HEIGHT - 405,
        backgroundColor: Colors.appBackground,
        paddingLeft: 20,
        paddingRight: 10,
    },
    listview: {
        flex: 1,
        flexDirection: 'row',
        marginBottom: 3,
    },
    defaultView: {
        justifyContent: 'center',
        alignItems: 'center',
        padding: 20,
    },
    defaultViewTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        marginBottom: 15,
    },
    renderrowtextcontainer: {
        width: WINDOW_WIDTH-50,
    },
    renderrowimage: {
        margin: 4,
        width: 50,
        height: 50,
    },
    renderrowtext: {
        marginTop: 4,
        marginLeft: 4,
        fontSize: 12,
        color: '#CDCD00',
    },
    listTitle: {
        paddingRight: 3,
        alignItems:'center',
        justifyContent: 'center',
        borderRightWidth: 1,
        borderRightColor: Colors.mySplitter,
    }
});

export default My;